package com.eryos.android.cigarettecounter.widget;

import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.eryos.android.cigarettecounter.database.CigaretteDatabase;

/**
 * Project : CigaretteCounter Author : Olivier Combe URL : http://eryos.fr/CigaretteCounter/
 * 
 * Copyright(C)2011 - Olivier Combe
 * 
 * Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * 
 * @version \$Revision.*\$
 * @author Olivier Combe
 */
public class CigaretteCounterWidger extends AppWidgetProvider {

    private static final String LOG_TAG = "CigaretteCounterWidger";

    /**
     * {@inheritDoc} Method call for ACTION_APPWIDGET_UPDATE intents.
     */
    @Override
    public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {

        Log.d(LOG_TAG, "onUpdate method called");
        // Get all ids
        ComponentName thisWidget = new ComponentName(context, CigaretteCounterWidger.class);
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

        // Build the intent to call the service
        Intent intent = new Intent(context.getApplicationContext(), UpdateWidgetService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

        // Update the widgets via the service
        context.startService(intent);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.d(LOG_TAG, "onReceive method called : " + intent.getAction());

        // If Intent is dedicated to DB action
        if (intent != null && intent.getAction() != null
                && intent.getAction().equalsIgnoreCase(UpdateWidgetService.INCREASE_ACTION)) {
            Log.i(LOG_TAG, "Increase action ...");

            // Open DB and insert new cigarette record
            CigaretteDatabase db = CigaretteDatabase.getInstance(context);
            db.open();
            if (db != null) {
                db.insertCurrentTimestamp("", 0);
                Log.d(LOG_TAG, "insert DB OK");
                // db.close();
            }

            // Update all widgets
            updateAllWidgets(context);

        } else {

            // If it's another intent, follow the 'normal' process
            super.onReceive(context, intent);
        }
    }

    /**
     * Method used to create and send an Update Intent for all widgets.
     * 
     * @param context
     *            application Context
     */
    public static void updateAllWidgets(final Context context) {
        Log.d(LOG_TAG, "updateAllWidgets");

        // Prepare a new intent to refresh widgets
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        ComponentName thisWidget = new ComponentName(context, CigaretteCounterWidger.class);
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

        Intent intentUpdate = new Intent(context, CigaretteCounterWidger.class);
        intentUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intentUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

        try {
            PendingIntent.getBroadcast(context, 0, intentUpdate, PendingIntent.FLAG_UPDATE_CURRENT).send();
        } catch (CanceledException e) {
            Log.e(LOG_TAG, "<updateAllWidgets> Exception", e);
        }
    }

    /**
     * Method used to create an intent that will be used when clicking on widget(or widget component).
     * 
     * @param ctx
     *            application Context
     * @param allWidgetIds
     *            list of Widget's IDs
     * @return PendingIntent ready to be attach with setOnClickPendingIntent method
     */
    public static PendingIntent createClickPendingIntent(final Context ctx, final int[] allWidgetIds) {
        // Register an onClickListener
        Intent clickIntent = new Intent(ctx, CigaretteCounterWidger.class);

        clickIntent.setAction(UpdateWidgetService.INCREASE_ACTION);
        clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

        PendingIntent pendingIntent = PendingIntent
                .getBroadcast(ctx, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        return pendingIntent;
    }

}
